var app = getApp();
Page({
  data: {
    //标签列表
    labelList: [],
    //隐藏输入框
    labelInput: true,
    //增加话题输入框value
    newValue: ''
  },
  onLoad: function() {
    //找到系统状态位置
    this.setData({
      statusBarHeight: app.globalData.systemInfo.statusBarHeight + 15
    })
    this.getLabelList();
  },


  //创建新话题
  openLabelBox: function() {
    this.setData({
      labelInput: false
    })
  },


  //创建完毕
  toastConfirm: function() {
    var newValue = this.data.newValue;
    if (newValue != '') {
      var label = {
        content: newValue
      }
      //获取页面值栈
      var pages = getCurrentPages();
      //上一个页面
      var lastPage = pages[pages.length - 2];
      lastPage.setData({
        label: label
      })
      this.rollback();

      wx.request({
        url: app.globalData.requestUrl + 'addLabel',
        method: 'POST',
        data: {
          userId: app.globalData.user.id,
          content: newValue
        }
      })
    }

  },

  //取消创建
  toastCancel: function() {
    this.setData({
      labelInput: true
    })
  },
  //监听输入框
  setValue: function(e) {
    var value = e.detail.detail.value;
    var cursor = e.detail.detail.cursor;
    //不能超过500
    if (cursor > 8) {
      this.setData({
        newValue: value.substring(0, 8)
      })
    } else {
      this.setData({
        newValue: value
      })
    }
  },

  //查询标签
  getLabelList: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getLabelList',
      method: 'GET',
      success: function(r) {
        if (r.data.code == 200) {
          that.setData({
            labelList: r.data.data
          })
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络连接失败,请稍后重试',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  //选择标签
  selectLabel: function(e) {
    var index = e.currentTarget.dataset.index;
    var label = this.data.labelList[index];
    //获取页面值栈
    var pages = getCurrentPages();
    //上一个页面
    var lastPage = pages[pages.length - 2];
    lastPage.setData({
      label: label
    })
    this.rollback();
  },

  //返回下一个页面
  rollback: function() {
    wx.navigateBack({
      delta: 1
    })
  }
})